/**
 * JAVACC DEMO 1.0
 */
package com.apache.info.service.plugins;

import com.alibaba.druid.pool.DruidDataSource;
import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.database.datasource.ConnctionData;
import com.apache.database.datasource.DynamicDataSource;
import com.apache.database.datasource.DynamicDataSourceHolder;
import com.apache.info.entity.PubSortInfo;
import com.apache.info.manager.InfoReleaseManager;
import com.apache.info.manager.PubSortInfoManager;
import com.apache.info.util.MessageUtil;
import com.apache.tools.StrUtil;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * description:  动态创建数据库操作
 *
 * @author Hou Dayu 创建时间：2016-8-28
 */
public class DynamicCreateDataBasePluginImpl implements PluginConnector {

	private InfoReleaseManager infoReleaseManager;

	/**
	 * TODO 动态删除表插件实现.
	 *
	 * @see PluginConnector#execute(ParamsVo)
	 */
	public Object execute(ParamsVo vo) throws Exception {
		String useDatasource = StrUtil.doNull(String.valueOf(vo.getParams("useDatasource")),"plateform");
		String databaseName = String.valueOf(vo.getParams("databaseName"));
		DruidDataSource bds = DynamicDataSource.getInstance().getDataSource(useDatasource);
		boolean mark = false;
		try {
			String dbType = MessageUtil.getDatabastType(useDatasource, bds.getDriverClassName());
			Connection con = bds.getConnection();
			String sql = createDatabaseSql(databaseName,dbType);
			if(StrUtil.isNotNull(sql)) {
				mark = ConnctionData.getInstance().execute(con, sql);
			}
		}catch (SQLException e){
			DynamicDataSource.getInstance().removeDataSource(databaseName);
			return false;
		}
		return mark;
	}

	private String createDatabaseSql(String databaseName,String dbType) {
		String sql = null;
		if("oracle".equals(dbType)){
			sql = "CREATE DATABASE "+databaseName;
		} else {
			sql = "CREATE DATABASE IF NOT EXISTS "+databaseName+" default charset utf8 COLLATE utf8_general_ci";
		}
		return sql;
	}

	public void setInfoReleaseManager(InfoReleaseManager infoReleaseManager) {
		this.infoReleaseManager = infoReleaseManager;
	}

}
